package leetcode;

import org.junit.Test;

import java.util.HashMap;

/**
 * 无重复字符的最长子串  
 */
public class LeetCode3 {
    @Test
    public void t1() {
        System.out.println(lengthOfLongestSubstring("a"));
    }

    @Test
    public void t2() {
        System.out.println(lengthOfLongestSubstring("ab"));
    }

    @Test
    public void t3() {
        System.out.println(lengthOfLongestSubstring("bbbbb"));
    }

    @Test
    public void t4() {
        System.out.println(lengthOfLongestSubstring("abcabcbb"));
    }

    @Test
    public void t5() {
        System.out.println(lengthOfLongestSubstring("pwwkew"));
    }

    public int lengthOfLongestSubstring(String s) {
        HashMap<Character, Integer> map = new HashMap<Character, Integer>();
        int res = 0, i = 0, j = 0, len = s.length();
        while (i < len && j < len) {
            char c = s.charAt(j);
            if (!map.containsKey(c) || map.get(c) < i) {
                map.put(c, j++);
            } else {
                i = map.get(c) + 1;
            }
            res = Math.max(res, j - i);
        }
        return res;
    }

}
